package com.starhub.engine.function.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starhub.common.bean.ID;
import com.starhub.engine.ai.dto.AiFunctionDTO;
import com.starhub.engine.ai.enums.AiFunctionTypeEnum;
import com.starhub.engine.ai.vo.AiFunctionVO;
import com.starhub.application.function.biz.AiFunctionProvider;
import com.starhub.application.interfaces.function.IAiFunctionService;
import com.starhub.common.bean.ResultResp;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.common.security.util.SecurityUtils;

import com.starhub.utils.Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * AI函数控制器
 * 提供AI函数的CRUD操作接口
 */
@Slf4j
@RestController
@RequestMapping("/engine/starhub/function")
@RequiredArgsConstructor
public class AiFunctionController {

    private final IAiFunctionService aiFunctionService;
    private final AiFunctionProvider aiFunctionProvider;

    /**
     * 获取函数类型列表
     *
     * @return 函数类型列表
     */
    @GetMapping("/types")
    public ResultResp<List<Map<String, String>>> listTypes() {
        List<Map<String, String>> types = Arrays.stream(AiFunctionTypeEnum.values())
                .map(type -> Map.of(
                        "code", type.getCode(),
                        "desc", type.getDesc()))
                .collect(Collectors.toList());
        return ResultResp.success(types);
    }

    /**
     * 分页查询函数列表
     *
     * @param page 页码，从1开始
     * @param size 每页大小
     * @param name 函数名称，可为空
     * @param type 函数类型，可为空
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResultResp<IPage<AiFunctionVO>> pageFunctions(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type) {
        IPage<AiFunctionVO> pageResult = aiFunctionService.pageFunctions(page, size, name, type);
        return ResultResp.success(pageResult);
    }

    /**
     * 获取函数详情
     *
     * @param id 函数ID
     * @return 函数详情
     */
    @GetMapping("/{id}")
    public ResultResp<AiFunctionVO> getFunctionDetail(@PathVariable Long id) {
        AiFunctionVO function = aiFunctionService.getFunctionDetail(id);
        if (function == null) {
            return ResultResp.fail("函数不存在");
        }
        return ResultResp.success(function);
    }

    /**
     * 新增函数
     *
     * @param functionDTO 函数DTO对象
     * @return 操作结果
     */
    @PostMapping("/add")
    public ResultResp<Boolean> addFunction(@RequestBody AiFunctionDTO functionDTO) {
        try {
            // 获取当前用户信息
            LoginUser loginUser = SecurityUtils.getCurrentUser();
            String operatorId = "system";
            String operatorName = "系统";
            if (loginUser != null && loginUser.getUser() != null) {
                operatorId = loginUser.getUserId();
                operatorName = loginUser.getUsername();
            }

            boolean result = aiFunctionService.addFunction(functionDTO, operatorId, operatorName);
            return result ? ResultResp.success(null) : ResultResp.fail("新增函数失败");
        } catch (Exception e) {
            log.error("新增函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 更新函数
     *
     * @param functionDTO 函数DTO对象
     * @return 操作结果
     */
    @PostMapping("/update")
    public ResultResp<Boolean> updateFunction(@RequestBody @Valid AiFunctionDTO functionDTO) {
        try {
            // 获取当前用户信息
            LoginUser loginUser = SecurityUtils.getCurrentUser();
            String operatorId = "system";
            String operatorName = "系统";
            if (loginUser != null && loginUser.getUser() != null) {
                operatorId = loginUser.getUserId();
                operatorName = loginUser.getUsername();
            }

            boolean result = aiFunctionService.updateFunction(functionDTO, operatorId, operatorName);
            return result ? ResultResp.success(null) : ResultResp.fail("更新函数失败");
        } catch (Exception e) {
            log.error("更新函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 删除函数
     *
     * @param id 函数ID
     * @return 操作结果
     */
    @PostMapping("/delete/{id}")
    public ResultResp<Boolean> deleteFunction(@PathVariable Long id) {
        try {
            boolean result = aiFunctionService.deleteFunction(id);
            return result ? ResultResp.success(null) : ResultResp.fail("删除函数失败");
        } catch (Exception e) {
            log.error("删除函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }


    /**
     * 删除函数
     *
     * @param id 函数ID
     * @return 操作结果
     */
    @PostMapping("/batchDelete/{id}")
    public ResultResp<Boolean> batchDeleteFunction(@RequestBody ID id) {
        try {
            boolean result = aiFunctionService.deleteFunction(Util.getLongValue(id.getId()));
            return result ? ResultResp.success(null) : ResultResp.fail("删除函数失败");
        } catch (Exception e) {
            log.error("删除函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 启用函数
     *
     * @param id 函数ID
     * @return 操作结果
     */
    @PostMapping("/enable/{id}")
    public ResultResp<Boolean> enableFunction(@PathVariable Long id) {
        try {
            // 获取当前用户信息
            LoginUser loginUser = SecurityUtils.getCurrentUser();
            String operatorId = "system";
            String operatorName = "系统";
            if (loginUser != null && loginUser.getUser() != null) {
                operatorId = loginUser.getUserId();
                operatorName = loginUser.getUsername();
            }

            boolean result = aiFunctionService.enableFunction(id, operatorId, operatorName);
            return result ? ResultResp.success(null) : ResultResp.fail("启用函数失败");
        } catch (Exception e) {
            log.error("启用函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 禁用函数
     *
     * @param id 函数ID
     * @return 操作结果
     */
    @PostMapping("/disable/{id}")
    public ResultResp<Boolean> disableFunction(@PathVariable Long id) {
        try {
            // 获取当前用户信息
            LoginUser loginUser = SecurityUtils.getCurrentUser();
            String operatorId = "system";
            String operatorName = "系统";
            if (loginUser != null && loginUser.getUser() != null) {
                operatorId = loginUser.getUserId();
                operatorName = loginUser.getUsername();
            }

            boolean result = aiFunctionService.disableFunction(id, operatorId, operatorName);
            return result ? ResultResp.success(null) : ResultResp.fail("禁用函数失败");
        } catch (Exception e) {
            log.error("禁用函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 测试执行函数
     *
     * @param functionName 函数名称
     * @param arguments    函数参数
     * @return 执行结果
     */
    @PostMapping("/{functionName}")
    public ResultResp<String> testFunction(@PathVariable String functionName, @RequestBody Map<String, Object> arguments) {
        try {
            String result = aiFunctionProvider.executeFunction(functionName, arguments);
            return ResultResp.success(result);
        } catch (Exception e) {
            log.error("测试函数失败", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 获取所有启用状态的函数定义列表
     * 用于前端展示和调试
     *
     * @return 函数定义列表
     */
    @GetMapping("/schemas")
    public ResultResp<List<Map<String, Object>>> getFunctionSchemas() {
        List<Map<String, Object>> schemas = aiFunctionProvider.getFunctionSchemas();
        return ResultResp.success(schemas);
    }
}